package com.loan.market.http

import android.os.Build
import android.provider.Settings
import com.google.gson.reflect.TypeToken
import com.loan.market.LoanApp.Companion.application
import com.loan.market.util.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.http.Body
import retrofit2.http.POST
import retrofit2.http.Url

typealias HttpMap = MutableMap<String, Any?>

fun getHttpMap(messageId: Int): HttpMap {
    return mutableMapOf("messageId" to messageId)
}

lateinit var apiService: ApiService

fun getApi(): ApiService {
    if (::apiService.isInitialized) {
        return apiService
    }
    apiService = Retrofit.getInstance("https://api.dineroflash.co/").create(ApiService::class.java)
    return apiService
}

suspend inline fun <reified T> request(map: HttpMap, url: String = ApiService.path1): T? {
    map.let {
        it["appId"] = 1001
        it["country"] = "54"
        it["language"] = "sp"
        it["appsflyerId"] = getAfId()
        it["packageName"] = application.packageName
        it["appVersion"] = application.getAppVersion()
        it["deviceId"] = Settings.System.getString(application.contentResolver, Settings.Secure.ANDROID_ID)
        it["osVersion"] = "Android" + Build.VERSION.RELEASE
        it["osType"] = "Android"
        if (UserUtil.isLogin()) {
            it["userId"] = UserUtil.getUserId()
        }
    }
    val json = getApi().getResponse(url, map.toJson().encrypt().toRequestBody("application/json".toMediaType())).string()
    val jsonObject = JSONObject(json)
    val code = jsonObject.optInt("code", -1)
    if (code != 0) {
        throw Exception(jsonObject.optString("message"))
    }
    if (jsonObject.isNull("result")) return null
    val result = jsonObject.optString("result")
    return GsonUtil.getInstance().fromJson(result.decrypt(), object : TypeToken<T>() {}.type)
}

interface ApiService {

    @POST
    suspend fun getResponse(@Url url: String, @Body map: RequestBody): ResponseBody

    companion object {
        const val path1 = "ad20aa2602"
        const val path2 = "c7114db95f"
        const val path3 = "fff73c34a0"
        const val path4 = "b5d9ec4f97"
        const val path5 = "c1227be368"
    }
}
